//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using EffiProzDB.Lib;
using System.Collections.Generic;

namespace EffiProzDB.Persist
{
    /**
     * Manages a .properties file for a database.
     *
     * @author fredt@users
     * @version 1.8.0
     * @since 1.7.0
     */
    public class HsqlDatabaseProperties : HsqlProperties
    {
        private static string hsqldb_method_class_names = "hsqldb.method_class_names";
        private static HashSet<string> accessibleJavaMethodNames;

        static HsqlDatabaseProperties()
        {
            try
            {
                string prop = Environment.GetEnvironmentVariable(hsqldb_method_class_names);

                if (prop != null)
                {
                    accessibleJavaMethodNames = new HashSet<string>();

                    string[] names = prop.Split(";".ToCharArray());

                    foreach (var name in names)
                    {
                        accessibleJavaMethodNames.Add(name);
                    }
                }
            }
            catch (Exception ) { }


            // string defaults for protected props
            meta.Add(db_version, getMeta(db_version, FILE_PROPERTY, null));
            meta.Add(hsqldb_compatible_version,
                     getMeta(hsqldb_compatible_version, FILE_PROPERTY, null));
            meta.Add(hsqldb_cache_version,
                     getMeta(hsqldb_cache_version, FILE_PROPERTY, null));
            meta.Add(hsqldb_original_version,
                     getMeta(hsqldb_original_version, FILE_PROPERTY, null));
            meta.Add(db_modified, getMeta(db_modified, FILE_PROPERTY, null));

            // string defaults for user defined props
            meta.Add(hsqldb_default_table_type,
                     getMeta(hsqldb_default_table_type, SET_PROPERTY, "memory"));
            meta.Add(textdb_fs, getMeta(textdb_fs, SET_PROPERTY, ","));
            meta.Add(textdb_vs, getMeta(textdb_vs, SET_PROPERTY, null));
            meta.Add(textdb_lvs, getMeta(textdb_lvs, SET_PROPERTY, null));
            meta.Add(textdb_encoding,
                     getMeta(textdb_encoding, SET_PROPERTY, null));

            // bool defaults for protected props
            meta.Add(db_readonly, getMeta(db_readonly, FILE_PROPERTY, false));
            meta.Add(hsqldb_files_readonly,
                     getMeta(hsqldb_files_readonly, FILE_PROPERTY, false));
            meta.Add(textdb_allow_full_path,
                     getMeta(textdb_allow_full_path, FILE_PROPERTY, false));

            // bool defaults for user defined props
            meta.Add(hsqldb_lock_file,
                     getMeta(hsqldb_lock_file, SET_PROPERTY, true));
            meta.Add(hsqldb_nio_data_file,
                     getMeta(hsqldb_nio_data_file, SET_PROPERTY, false));
            meta.Add(hsqldb_catalogs,
                     getMeta(hsqldb_catalogs, SET_PROPERTY, false));
            meta.Add(sql_enforce_strict_size,
                     getMeta(sql_enforce_strict_size, SET_PROPERTY, true)); //defaul enfoece strict size
            meta.Add(sql_tx_no_multi_write,
                     getMeta(sql_tx_no_multi_write, SET_PROPERTY, false));
            meta.Add(textdb_quoted, getMeta(textdb_quoted, SET_PROPERTY, false));
            meta.Add(textdb_all_quoted,
                     getMeta(textdb_all_quoted, SET_PROPERTY, false));
            meta.Add(textdb_ignore_first,
                     getMeta(textdb_ignore_first, SET_PROPERTY, false));

            // integral defaults for user-defined set props
            meta.Add(hsqldb_applog,
                     getMeta(hsqldb_applog, SET_PROPERTY, 0, new byte[] {
            0, 1, 2
        }));
            meta.Add(hsqldb_cache_file_scale,
                     getMeta(hsqldb_cache_file_scale, SET_PROPERTY, 1, new byte[] {
            1, 8
        }));
            meta.Add(hsqldb_script_format,
                     getMeta(hsqldb_script_format, SET_PROPERTY, 0, new byte[] {
            0, 1, 3
        }));

            // integral defaults for proteced range props
            meta.Add(hsqldb_log_size,
                     getMeta(hsqldb_log_size, SQL_PROPERTY, 0, 0, 16000));
            meta.Add(hsqldb_defrag_limit,
                     getMeta(hsqldb_defrag_limit, SQL_PROPERTY, 200, 0, 16000));

            // integral defaults for user defined range props
            meta.Add(runtime_gc_interval,
                     getMeta(runtime_gc_interval, SET_PROPERTY, 0, 0, 1000000));
            meta.Add(hsqldb_cache_free_count_scale,
                     getMeta(hsqldb_cache_free_count_scale, SET_PROPERTY, 9, 6,
                             12));
            meta.Add(hsqldb_cache_scale,
                     getMeta(hsqldb_cache_scale, SET_PROPERTY, 14, 8, 18));
            meta.Add(hsqldb_cache_size_scale,
                     getMeta(hsqldb_cache_size_scale, SET_PROPERTY, 10, 6, 20));
            meta.Add(hsqldb_max_nio_scale,
                     getMeta(hsqldb_max_nio_scale, SET_PROPERTY, 28, 24, 31));
            meta.Add(hsqldb_raf_buffer_scale,
                     getMeta(hsqldb_raf_buffer_scale, SET_PROPERTY, 12, 8, 13));
            meta.Add(textdb_cache_scale,
                     getMeta(textdb_cache_scale, SET_PROPERTY, 10, 8, 16));
            meta.Add(textdb_cache_size_scale,
                     getMeta(textdb_cache_size_scale, SET_PROPERTY, 10, 6, 20));
        }

        /**
         * If the system property "hsqldb.method_class_names" is not set, then
         * static methods of all available Java classes can be accessed as functions
         * _in HSQLDB. If the property is set, then only the list of semicolon
         * seperated method names becomes accessible. An empty property value means
         * no class is accessible.<p>
         *
         * A property value that ends with .* is treated as a wild card and allows
         * access to all classe or method names formed by substitution of the
         * asterisk.<p>
         *
         * All methods of org.hsqldb.Library and java.lang.Math are always
         * accessible.
         *
         *
         */
        public static bool supportsJavaMethod(string name)
        {

            if (accessibleJavaMethodNames == null)
            {
                return true;
            }

            if (name.StartsWith("org.hsqldb.Library."))
            {
                return true;
            }

            if (name.StartsWith("java.lang.Math."))
            {
                return true;
            }

            if (accessibleJavaMethodNames.Contains(name))
            {
                return true;
            }
        
            foreach (var className in accessibleJavaMethodNames)
            {               
                int limit = className.LastIndexOf(".*");

                if (limit < 1)
                {
                    continue;
                }

                if (name.StartsWith(className.Substring(0, limit + 1 - (0))))
                {
                    return true;
                }
            }

            return false;
        }

        // column number mappings
        public const int indexName = 0;
        public const int indexAccess = 1;
        public const int indexClass = 2;
        public const int indexIsRange = 3;
        public const int indexDefaultValue = 4;
        public const int indexRangeLow = 5;
        public const int indexRangeHigh = 6;
        public const int indexValues = 7;
        public const int indexLimit = 8;

        // accessibility
        private  const int SET_PROPERTY = 0;
        private  const int SQL_PROPERTY = 1;
        private  const int FILE_PROPERTY = 2;

        // db files modified
        public  const int FILES_NOT_MODIFIED = 0;
        public  const int FILES_MODIFIED = 1;
        public  const int FILES_NEW = 2;
        private const string MODIFIED_NO = "no";
        private const string MODIFIED_YES = "yes";
        private const string MODIFIED_NEW = "no-new-files";

        // allowed property metadata
        private static Dictionary<string, object[]> meta = new Dictionary<string, object[]>();

        // versions
        public const string VERSION_STRING_1_7_0 = "1.7.0";
        public const string VERSION_STRING_1_8_0 = "1.8.0";
        public const string FIRST_COMPATIBLE_VERSION = "1.8.0";
        public const string THIS_VERSION = "1.8.0";
        public const string THIS_FULL_VERSION = "1.8.0.10";
        public const string THIS_CACHE_VERSION = "1.7.0";
        public const string PRODUCT_NAME = "EffiProz Database Engine";
        public const int MAJOR = 0, MINOR = 1, REVISION = 0;

        /**
         * system properties supported by HSQLDB
         */
        public const string system_lockfile_poll_retries_property =
            "hsqldb.lockfile_poll_retries";
        public const string system_max_char_or_varchar_display_size =
            "hsqldb.max_char_or_varchar_display_size";

        //
        public const string db_version = "version";
        private const string db_readonly = "readonly";
        private  const string db_modified = "modified";

        //
        private const string runtime_gc_interval = "runtime.gc_interval";
        public const string hsqldb_applog = "hsqldb.applog";
        public const string hsqldb_cache_file_scale =
            "hsqldb.cache_file_scale";
        public const string hsqldb_cache_free_count_scale =
            "hsqldb.cache_free_count_scale";
        public const string hsqldb_cache_scale = "hsqldb.cache_scale";
        public const string hsqldb_cache_size_scale =
            "hsqldb.cache_size_scale";
        public const string hsqldb_cache_version = "hsqldb.cache_version";
        private const string hsqldb_catalogs = "hsqldb.catalogs";
        public const string hsqldb_compatible_version =
            "hsqldb.compatible_version";
        public const string hsqldb_default_table_type =
            "hsqldb.default_table_type";
        public const string hsqldb_defrag_limit = "hsqldb.defrag_limit";
        private const string hsqldb_files_readonly =
            "hsqldb.files_readonly";
        public const string hsqldb_lock_file = "hsqldb.lock_file";
        public const string hsqldb_log_size = "hsqldb.log_size";
        public const string hsqldb_nio_data_file = "hsqldb.nio_data_file";
        public const string hsqldb_max_nio_scale = "hsqldb.max_nio_scale";
        public const string hsqldb_raf_buffer_scale =
            "hsqldb.raf_buffer_scale";
        private  const string hsqldb_original_version =
            "hsqldb.original_version";
        public const string hsqldb_script_format = "hsqldb.script_format";

        //
        private  const string sql_compare_in_locale =
            "sql.compare_in_locale";
        public const string sql_enforce_strict_size =
            "sql.enforce_strict_size";
        public const string sql_tx_no_multi_write =
            "sql.tx_no_multi_rewrite";

        //
        public const string textdb_cache_scale = "textdb.cache_scale";
        public const string textdb_cache_size_scale =
            "textdb.cache_size_scale";
        public const string textdb_all_quoted = "textdb.all_quoted";
        public const string textdb_allow_full_path =
            "textdb.allow_full_path";
        public const string textdb_encoding = "textdb.encoding";
        public const string textdb_ignore_first = "textdb.ignore_first";
        public const string textdb_quoted = "textdb.quoted";
        public const string textdb_fs = "textdb.fs";
        public const string textdb_vs = "textdb.vs";
        public const string textdb_lvs = "textdb.lvs";

     
        private Database database; 

        public HsqlDatabaseProperties(Database db)
            : base(db.getPath(), db.getFileAccess())
        {

            database = db;  

            // char padding to size and exception if data is too long
            setProperty(sql_enforce_strict_size, false);

            // removed from 1.7.2 - sql.month is always true (1-12)
            // removed from 1.7.2 - sql.strict_fk is always enforced
            // if true, requires a pre-existing unique index for foreign key
            // referenced column and returns an error if index does not exist
            // 1.61 creates a non-unique index if no index exists
            // setProperty("sql.strict_fk", false);
            // removed from 1.7.2
            // has no effect if sql_strict_fk is true, otherwise if true,
            // creates a unique index for foreign keys instead of non-unique
            // setProperty("sql.strong_fk", true);
            // the two properties below are meant for attempting to open an
            // existing database with all its files *.properties, *script and
            // *.data.
            // version of a new database
            setProperty(db_version, THIS_VERSION);

            // the earliest version that can open this database
            // this is set to 1.7.2 when the db is written to
            setProperty(hsqldb_compatible_version, FIRST_COMPATIBLE_VERSION);

            // data format of the cache file
            // this is set to 1.7.0 when a new *.data file is created
            setProperty(hsqldb_cache_version, THIS_CACHE_VERSION);

            // the version that created this database
            // once created, this won't change if db is used with a future version
            setProperty(hsqldb_original_version, THIS_VERSION);
            /*
                    garbage collection with gc_interval
                    Setting this value can be useful when HSQLDB is used as an
                    in-process part of an application. The minimum practical
                    amount is probably "10000" and the maximum "1000000"

                    In some versions of Java, such as 1.3.1_02 on windows,
                    when the application runs _out of memory it runs the gc AND
                    requests more memory from the OS. Setting this property
                    forces the DB to live inside its memory budget but the
                    maximum amount of memory can still be set with the
                    java -Xmx argument to provide the memory needed by other
                    parts of the app to do graphics and networking.

                    Of course there is a speed penalty for setting the value
                    too low and doing garbage collection too often.

                    This was introduced as a result of tests by Karl Meissner
                    (meissnersd@users)
             */

            // garbage collect per Record or Cache Row objects created
            // the default, "0" means no garbage collection is forced by
            // hsqldb (the Java Runtime will do it's own garbage collection
            // _in any case).
            setProperty(runtime_gc_interval, 0);

            // this property is either 1 or 8
            setProperty(hsqldb_cache_file_scale, 1);

            // this property is between 6 - 20, default 8
            setProperty(hsqldb_cache_size_scale, 8);

            // number of rows from CACHED tables kept constantly _in memory
            // the number of rows _in up to 3 * (2 to the power of
            // cache_scale value).
            // reduce the default 14 (3*16K rows) if memory is limited and rows
            // are large.
            // values between 8-16 are allowed
            setProperty(hsqldb_cache_scale, 14);

            // maximum size of .log file _in megabytes
            setProperty(hsqldb_log_size, 200);

            // type of logging (0 : text , 1 : binary, 3 : compressed)
            setProperty(hsqldb_script_format, 0);
            setProperty(db_readonly, false);
            setProperty(db_modified, "no-new-files");

            // initial method of data file access
            setProperty(hsqldb_nio_data_file, false);

            // set default table type to MEMORY
            setProperty(hsqldb_default_table_type, "memory");

            // the property "version" is also set to the current version
            //
            // the following properties can be set by the user as defaults for
            // text tables. the default values are shown.
            // "textdb.fs", ","
            // "textdb.vs", ",";
            // "textdb.lvs", ","
            // "textdb.ignore_first", false
            // "textdb.quoted", true
            // "textdb.all_quoted", false
            // "textdb.encoding", "ASCII"
            // "textdb.cache_scale", 10  -- allowed range 8-16
            // "textdb.cache_size_scale", 10  -- allowed range 8-20
            //
            // OOo related code
            if (db.isStoredFileAccess())
            {
                setProperty(hsqldb_default_table_type, "cached");
                setProperty(hsqldb_cache_scale, 13);
                setProperty(hsqldb_log_size, 10);
                setProperty(sql_enforce_strict_size, true);
                setProperty(hsqldb_nio_data_file, false);
            }

            // OOo end
        }

        /**
         * Creates file with defaults if it didn't exist.
         * Returns false if file already existed.
         */
        public override bool load()
        {

            bool exists;

            if (!DatabaseURL.isFileBasedDatabaseType(database.getType()))
            {
                return true;
            }

            try
            {
                exists = base.load();
            }
            catch (Exception e)
            {
                throw Trace.error(Trace.FILE_IO_ERROR, Trace.LOAD_SAVE_PROPERTIES,
                                  new Object[] {
                fileName, e
            });
            }

            if (!exists)
            {
                return false;
            }

            filterLoadedProperties();

            string version = getProperty(hsqldb_compatible_version);

            // do not open if the database belongs to a later (future) version
            int check = version.Substring(0, 5 - (0)).CompareTo(THIS_VERSION);

            if (check > 0)
            {
                throw Trace.error(Trace.WRONG_DATABASE_FILE_VERSION);
            }

            version = getProperty(db_version);

            if (version[(2)] == '6')
            {
                setProperty(hsqldb_cache_version, "1.6.0");
            }

            //JavaSystem.gcFrequency = getIntegerProperty(runtime_gc_interval, 0);

            return true;
        }

        /**
         * Sets the database member variables after creating the properties object,
         * openning a properties file, or changing a property with a command
         */
        public void setDatabaseVariables()
        {

            if (isPropertyTrue(db_readonly))
            {
                database.setReadOnly();
            }

            if (isPropertyTrue(hsqldb_files_readonly))
            {
                database.setFilesReadOnly();
            }

            database.sqlEnforceStrictSize =
                isPropertyTrue(sql_enforce_strict_size);

            if (isPropertyTrue(sql_compare_in_locale))
            {
                stringProps.Remove(sql_compare_in_locale);
                database.collation.setCollationAsLocale();
            }

            database.txManager.setReWriteProtection(   
                isPropertyTrue(sql_tx_no_multi_write));
            database.setMetaDirty(false);
        }

        public override void save()
        {

            if (!DatabaseURL.isFileBasedDatabaseType(database.getType())
                    || database.isFilesReadOnly() )
            {
                return;
            }

            try
            {
                base.save(fileName + ".properties" + ".new");
                fa.RenameElement(fileName + ".properties" + ".new",
                                 fileName + ".properties");
            }
            catch (Exception e)
            {
                //database.logger.appLog.logContext(SimpleLog.LOG_ERROR, "failed");   //TODOx

                throw Trace.error(Trace.FILE_IO_ERROR, Trace.LOAD_SAVE_PROPERTIES,
                                  new Object[] {
                fileName, e
            });
            }
        }

        void filterLoadedProperties()
        {

            var en = stringProps.Keys;

            foreach (var key in en)
            {

                bool accept = meta.ContainsKey(key);

                if (!accept)
                {
                    stringProps.Remove(key);
                }
            }
        }

        /**
         *  overload file database properties with any passed on URL line
         *  do not store password etc
         */
        public void setURLProperties(HsqlProperties p)
        {

            if (p != null)
            {
                foreach (var propertyName in p.propertyNames())
                {               
                    Object[] row ;

                    if (meta.TryGetValue(propertyName, out row))
                    {

                        if (row != null
                                && (db_readonly.Equals(propertyName)
                                    || ((int)row[indexAccess])
                                       == SET_PROPERTY))
                        {

                            // can add error checking with defaults
                            setProperty(propertyName, p.getProperty(propertyName));
                        }
                    }
                }
            }
        }

        public HashSet<object[]> getUserDefinedPropertyData()
        {
            HashSet<object[]> set = new HashSet<object[]>();         

            foreach (var row in meta.Values)
            {
                if (((int)row[indexAccess]) == SET_PROPERTY)
                {
                    set.Add(row);
                }
            }

            return set;
        }

        public bool isUserDefinedProperty(string key)
        {

            Object[] row = (Object[])meta[key];

            return row != null
                   && ((int)row[indexAccess]) == SET_PROPERTY;
        }

        public bool isbool(string key)
        {

            Object[] row = (Object[])meta[key];

            return row != null && row[indexClass].Equals("bool")
                   && ((int)row[indexAccess]) == SET_PROPERTY;
        }

        public bool isIntegral(string key)
        {

            Object[] row = (Object[])meta[key];

            return row != null && row[indexClass].Equals("int")
                   && ((int)row[indexAccess]) == SET_PROPERTY;
        }

        public bool isString(string key)
        {

            Object[] row = (Object[])meta[key];

            return row != null && row[indexClass].Equals("string")
                   && ((int)row[indexAccess]) == SET_PROPERTY;
        }

        public string setDatabaseProperty(string key,
                                          string value)
        {

            Object[] row = (Object[])meta[key];

            // can check bounds here
            value = base.setProperty(key, value);

            return value;
        }

        public int getDefaultWriteDelay()
        {

            // OOo related code
            if (database.isStoredFileAccess())
            {
                return 2000;
            }

            // OOo end
            return 10000;
        }

        public void setDBModified(int mode)
        {

            string value = MODIFIED_NO;

            if (mode == FILES_MODIFIED)
            {
                value = MODIFIED_YES;
            }
            else if (mode == FILES_NEW)
            {
                value = MODIFIED_NEW;
            }

            setProperty(db_modified, value);
            save();
        }

        public int getDBModified()
        {

            string value = getProperty("modified");

            if (MODIFIED_YES.Equals(value))
            {
                return FILES_MODIFIED;
            }
            else if (MODIFIED_NEW.Equals(value))
            {
                return FILES_NEW;
            }

            return FILES_NOT_MODIFIED;
        }

        private static Object[] getMeta(string name, int accessLevel,
                                        string defaultValue)
        {

            Object[] row = new Object[indexLimit];

            row[indexName] = name;
            row[indexAccess] = (accessLevel);
            row[indexClass] = "string";
            row[indexDefaultValue] = defaultValue;

            return row;
        }

        private static Object[] getMeta(string name, int accessLevel,
                                        bool defaultValue)
        {

            Object[] row = new Object[indexLimit];

            row[indexName] = name;
            row[indexAccess] =(accessLevel);
            row[indexClass] = "bool";
            row[indexDefaultValue] = defaultValue ? true
                                                  : false;

            return row;
        }

        private static Object[] getMeta(string name, int accessLevel,
                                        int defaultValue, byte[] values)
        {

            Object[] row = new Object[indexLimit];

            row[indexName] = name;
            row[indexAccess] = (accessLevel);
            row[indexClass] = "int";
            row[indexDefaultValue] = (defaultValue);
            row[indexValues] = values;

            return row;
        }

        private static Object[] getMeta(string name, int accessLevel,
                                        int defaultValue, int rangeLow,
                                        int rangeHigh)
        {

            Object[] row = new Object[indexLimit];

            row[indexName] = name;
            row[indexAccess] = (accessLevel);
            row[indexClass] = "int";
            row[indexDefaultValue] = (defaultValue);
            row[indexIsRange] = true;
            row[indexRangeLow] = (rangeLow);
            row[indexRangeHigh] = (rangeHigh);

            return row;
        }
    }
}
